package com.example.demo.func;

import com.example.demo.service.Assistant;
import com.example.demo.util.JsonUtil;
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.community.model.dashscope.QwenChatRequestParameters;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.request.json.JsonObjectSchema;
import dev.langchain4j.model.chat.response.ChatResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static com.example.demo.constant.ModelConstant.chatModelName;

@RestController
@RequiredArgsConstructor
@RequestMapping("/func/api")
public class FuncAPI {
    final Assistant assistant;

    final ChatLanguageModel chatLanguageModel;
    @GetMapping("/low/chat")
    public String lowChat(@RequestParam(value = "message")String message){
        ToolSpecification toolSpecification= ToolSpecification.builder()
                .name("Calculator")
                .description("输入俩个数，对这俩个数进行求和")
                .parameters(JsonObjectSchema.builder()
                        .addIntegerProperty("a","第一个参数")
                        .addIntegerProperty("b","第二个参数")
                        .required("a","b")
                        .build())
                .build();
        ChatResponse chatResponse = chatLanguageModel.doChat(ChatRequest.builder()
                .messages(List.of(UserMessage.from(message)))
                .parameters(QwenChatRequestParameters.builder()
                        .modelName(chatModelName)
                        .toolSpecifications(toolSpecification)
                        .build())
                .build());

        chatResponse.aiMessage().toolExecutionRequests().forEach(toolExecutionRequest -> {
            System.out.println(toolExecutionRequest.name());
            System.out.println(toolExecutionRequest.arguments());

            try {
                Class<?> aClass = Class.forName("com.example.demo.func." + toolExecutionRequest.name());
                Runnable josnObject=(Runnable) JsonUtil.toJsonObject(toolExecutionRequest.arguments(),aClass);
                josnObject.run();
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        });

        return chatResponse.aiMessage().text();
    }

    @GetMapping("/high/chat")
    public String highChat(@RequestParam(value = "message")String message){
        return assistant.chat(message);
    }
}
